//
//  CommendViewController.m
//  FreeTravel
//
//  Created by 徐康 on 16/8/26.
//  Copyright © 2016年 KX. All rights reserved.
#import "MBProgressHUD.h"
#import "MJRefreshHeader.h"
#import "WebViewOfCommendViewController.h"
#import "ModelOfCommendViewController.h"
#import "CollectionViewAlbum.h"
#import "CommendViewController.h"
#import "FreeTravelMacro.h"
#import "FreeTravelNetwork.h"
#import "ModelOfSildeCommend.h"
#import "SDImageCache.h"
#import "UIImageView+WebCache.m"
#import "FirstCellOfCommendTableViewCell.h"
#import "SecondCellOfCommend.h"
#import "CommendSearchViewController.h"
#import "MJRefreshFooter.h"
#import "MJRefresh.h"
#import "ModelOfEntryCommend.h"
#import "MJRefreshNormalHeader.h"

@interface CommendViewController ()<MBProgressHUDDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ModelOfCommendViewController *model;
@property (nonatomic, strong) NSMutableArray *arrOfHeadImage;
@property (nonatomic, strong) CollectionViewAlbum *album;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) UIButton *searchButton;
@end

@implementation CommendViewController
//定义一个全局变量用来持续加载
{
    NSInteger n;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.searchButton.hidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.searchButton.hidden = YES;
}
- (void)hudWasHidden:(MBProgressHUD*)hud {
    
    [self.hud removeFromSuperview];
    
    self.hud=nil;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
   
    n = 1;
    // 搜索按钮
    self.searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.searchButton.frame = CGRectMake(10, 5, SCREEN_WIDTH-20, 34);
    [self.navigationController.navigationBar addSubview:self.searchButton];
    [self.searchButton setTitle:@"搜索目的地、帖子、特价、FreeTraveler" forState:UIControlStateNormal];
    self.searchButton.titleLabel.font = [UIFont systemFontOfSize:13];
    self.searchButton.layer.borderColor = [UIColor whiteColor].CGColor;
    self.searchButton.layer.borderWidth = 1;
    self.searchButton.layer.cornerRadius = 10;
    self.searchButton.layer.masksToBounds = YES;
    [self.searchButton setImage:[UIImage imageNamed:@"fangdajing"] forState:UIControlStateNormal];
    self.searchButton.backgroundColor = COLORFORFREETRAVEL;
    self.searchButton.tintColor = [UIColor whiteColor];
    [self.searchButton addTarget:self action:@selector(goSearch) forControlEvents:UIControlEventTouchUpInside];
    
    [self handleData];
    [self createTableView];
    [self dropDownRefresh];
    [self drowDownLoad];
    
    self.hud = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:self.hud];
    self.hud.mode = MBProgressHUDModeAnnularDeterminate;
    
    self.hud.delegate = self;
    
    self.hud.label.text = @"Loading";
    
    [self.hud showAnimated:YES];
    [self.hud hideAnimated:YES afterDelay:2];

}
- (void)goSearch{
    CommendSearchViewController *vc = [[CommendSearchViewController alloc]init];
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:vc];
    [FreeTravelNetwork GET:@"http://open.qyer.com/qyer/search/hot_history?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=1&track_app_channel=App%2520Store&track_app_version=7.0.1&track_device_info=iPhone%25205s&track_deviceid=E9CA001A-5603-4CA8-B2EA-2BE34F691AC6&track_os=ios%25209.3.4&v=1" andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
        vc.arrayOfHot = [result objectForKey:@"data"];
    } andFailureBlock:^(NSError *error) {
        
    }];
    [self presentViewController:navi animated:YES completion:^{
        
    }];
}
- (void)handleData{
   [FreeTravelNetwork GET:@"http://open.qyer.com/qyer/home/home_feed?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&page=1&track_app_channel=App%2520Store&track_app_version=7.0.1&track_device_info=iPhone%25205s&track_deviceid=E9CA001A-5603-4CA8-B2EA-2BE34F691AC6&track_os=ios%25209.3.4&v=1" andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
       
       [self SaveData:result Name:@"CommendViewController"];
       
       NSMutableArray *array = [NSMutableArray array];
       self.model = [ModelOfCommendViewController modelWithDic:result];
           for (ModelOfSildeCommend *modelOfCommend in self.model.data.slide) {
               
               [_arrOfHeadImage addObject:modelOfCommend.photo];
               [array addObject:modelOfCommend.url];
           }
       self.album.arrOfImages = self.arrOfHeadImage;
       self.album.arrOfWebView = array;
       [self.tableView reloadData];
   } andFailureBlock:^(NSError *error) {
      NSDictionary *dic = [self LoadDicDataWithPath:@"CommendViewController"];
       self.model = [ModelOfCommendViewController modelWithDic:dic];
       NSMutableArray *array = [NSMutableArray array];
       for (ModelOfSildeCommend *modelOfCommend in self.model.data.slide) {
           
           [_arrOfHeadImage addObject:modelOfCommend.photo];
           [array addObject:modelOfCommend.url];
       }
       self.album.arrOfImages = self.arrOfHeadImage;
       self.album.arrOfWebView = array;
       [self.tableView reloadData];
   }];
}
#pragma mark - 下拉刷新
- (void)dropDownRefresh{
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handleNewData)];
}
-(void)handleNewData{
    self.model = [ModelOfCommendViewController modelWithDic:[NSDictionary dictionary]];
    
    
    [self handleData];
    
    [self.tableView.mj_header endRefreshing];
    
}
#pragma mark - 上拉加载
- (void)drowDownLoad{
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(handleMoreData)];
}
- (void)handleMoreData{
    
    n = n + 1;
    NSString *str = [NSString stringWithFormat:@"http://open.qyer.com/qyer/home/home_feed?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&page=%ld&track_app_channel=App%%2520Store&track_app_version=7.0.1&track_device_info=iPhone%%25205s&track_deviceid=E9CA001A-5603-4CA8-B2EA-2BE34F691AC6&track_os=ios%%25209.3.4&v=1",n ];
    [FreeTravelNetwork GET:str andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
        
        NSMutableArray *array =[[[result objectForKey:@"data"] objectForKey:@"feed"] objectForKey:@"entry"];
        for (NSDictionary *dic in array) {
            ModelOfEntryCommend *model = [ModelOfEntryCommend modelWithDic:dic];
            [self.model.data.feed.entry addObject:model];
        }
        
        [self.tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        
    }];
    
    [self.tableView.mj_footer endRefreshing];
    
}
- (void)createTableView{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[FirstCellOfCommendTableViewCell class] forCellReuseIdentifier:@"FirstCellOfCommendTableViewCell"];
    [self.tableView registerClass:[SecondCellOfCommend class] forCellReuseIdentifier:@"SecondCellOfCommend"];
    self.arrOfHeadImage = [NSMutableArray array];
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 244)];
    self.album = [[CollectionViewAlbum alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(10, 205, SCREEN_WIDTH-20, 34);
    
    [searchBtn setTitle:@"搜索目的地、帖子、特价、FreeTraveler" forState:UIControlStateNormal];
    searchBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    searchBtn.layer.borderColor = COLORFORFREETRAVEL.CGColor;
    searchBtn.layer.borderWidth = 1;
    searchBtn.layer.cornerRadius = 10;
    searchBtn.layer.masksToBounds = YES;
    [searchBtn setImage:[UIImage imageNamed:@"fangdajing"] forState:UIControlStateNormal];
    searchBtn.backgroundColor = [UIColor whiteColor];
    [searchBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(goSearch) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:searchBtn];
    [headView addSubview:self.album];
    self.tableView.tableHeaderView = headView;
    
    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    
   
    return self.model.data.feed.entry.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ModelOfEntryCommend *model = self.model.data.feed.entry[indexPath.row];
    
    if (model.username == nil) {
        FirstCellOfCommendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstCellOfCommendTableViewCell"];
        [cell setModel:model];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        SecondCellOfCommend *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondCellOfCommend"];
        [cell setModel:model];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y >= 200) {
        self.navigationController.navigationBar.hidden = NO;
    }else{
        self.navigationController.navigationBar.hidden = YES;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     ModelOfEntryCommend *model = self.model.data.feed.entry[indexPath.row];
    if (model.username == nil) {
        return 350;
    }else{
        return 400;
    }
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ModelOfEntryCommend *model = self.model.data.feed.entry[indexPath.row];
    WebViewOfCommendViewController *vc = [[WebViewOfCommendViewController alloc]init];
    vc.url = model.url;
    [self.navigationController pushViewController:vc animated:YES];
   }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
